//
//  RootViewController.m
//  Microtalk
//
//  Created by Dario Trisciuoglio on 18/03/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "RssFeedCell.h"
#import "ArtTBXMLViewController.h"
#import "ArticoloCommentiViewController.h"
#import "TBXML.h"

@implementation ArtTBXMLViewController
@synthesize listaTabella;
@synthesize spinner;
@synthesize spinnerView;

-(void)addIndicator{
    [self.view addSubview:spinnerView];
    [spinner startAnimating];
    [self.view setUserInteractionEnabled:NO];
}

-(void)removeIndicator{
    [spinner stopAnimating];
    [spinner release];    
    [spinnerView removeFromSuperview];
    [spinnerView release];
    [self.view setUserInteractionEnabled:YES];
}

- (void)applicaColore {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:1.0];
	self.spinnerView.backgroundColor = [UIColor clearColor];
	[UIView commitAnimations];
}

-(void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"lista"];
    [self addIndicator];
    URLparser = mobile_server_elenco_news;
    NSURL *url = [NSURL URLWithString:URLparser];
    [super performSelector:@selector(controlloDownloadXML) withObject:url afterDelay:0.01];
}

- (void)controlloDownloadXML{
    [self applicaColore];
    URLparser = mobile_server_elenco_news;
    NSURL *url = [NSURL URLWithString:URLparser];
    [super performSelector:@selector(removeIndicator) withObject:url afterDelay:0.01];
    //[self.listaTabella reloadData];
    [self loadURL];
}

- (void)loadURL {
    URLparser = mobile_server_elenco_news;
    NSURL *url = [NSURL URLWithString:URLparser];
    TBXML *tbxml = [[TBXML tbxmlWithURL:url] retain];
    elencoFeed = [[NSMutableArray alloc] initWithCapacity:10];
    [elencoFeed retain];
    
    if (tbxml.rootXMLElement)
        [self traverseElement:tbxml.rootXMLElement];
    [tbxml release];

}



- (void) traverseElement:(TBXMLElement *)element {
    
    do {
        //NSLog(@"%@",[TBXML elementName:element]);
               
        if (element->firstChild) 
            [self traverseElement:element->firstChild];
                
        if ([[TBXML elementName:element] isEqualToString:@"item"]) {

            TBXMLElement *titleElement = [TBXML childElementNamed:@"title" parentElement:element];
            TBXMLElement *linkElement = [TBXML childElementNamed:@"link" parentElement:element];
            TBXMLElement *descriptionElement = [TBXML childElementNamed:@"description" parentElement:element];
            TBXMLElement *imageURLElement = [TBXML childElementNamed:@"imageURL" parentElement:element];
            //NSLog(@"Titolo: %@ \n Descrizione: %@",[TBXML textForElement:titleElement],[TBXML textForElement:descriptionElement]);
            
            item = [[NSMutableDictionary alloc] init];
            [item setObject:[TBXML textForElement:titleElement] forKey:@"title"];
            [item setObject:[TBXML textForElement:linkElement] forKey:@"link"];
            [item setObject:[TBXML textForElement:descriptionElement] forKey:@"description"];
            [item setObject:[TBXML textForElement:imageURLElement] forKey:@"imageURL"];
           
            //salva tutte le proprietà del feed letto nell'elemento "item", per poi inserirlo nell'array "elencoFeed" 
            [elencoFeed addObject:item];
            }
        
   }
   
   while ((element = element->nextSibling));
  
   //int size = [elencoFeed count];
   //NSLog(@"ci sono %d oggetti in questo array", size);
   //NSLog(@"%@", elencoFeed);
    
    /* 
    NSString *s1 = @"link = ";
    NSString *s2 = @" world";
    NSString *ciao = [NSString stringWithFormat:@"%@%@", s1, s2];
    NSLog(@"%@", ciao);
    */
    
    [self.listaTabella reloadData];
}


-(void)autoDownload:(AutoDownloadImageView *)autoDowload didFailWithError:(NSError *)error {
	//NSLog(@"SOMETHING WRONG");
}



#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    //int size = [elencoFeed count];
    //NSLog(@"ci sono %d oggetti in questo array", size);
    //NSLog(@"%@", elencoFeed);
    return [elencoFeed count];
}

#pragma mark - UITableViewDelegate Methods

// prende l'altezza della cella nello xib 
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"RssFeedCell";
	
    RssFeedCell *cell = (RssFeedCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RssFeedCell" owner:self options:nil];
		
		for (id currentObject in topLevelObjects){
			if ([currentObject isKindOfClass:[UITableViewCell class]]){
				cell = (RssFeedCell *) currentObject;
				break;
			}
		}
	}
    
    // Metodo della classe AutoDownloadImageView molto meglio funziona
    id pathimg = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"imageURL"];
    pathimg = [pathimg stringByReplacingOccurrencesOfString:@" " withString:@""];
	pathimg = [pathimg stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	pathimg = [pathimg stringByReplacingOccurrencesOfString:@"	" withString:@""];
    
    //converto la stringa del link affinchè sia letta e caricata al posto dell'immagine
    NSURL *url = [NSURL URLWithString:pathimg];
	//controllo se l'url sia valida
    //if(!url) { NSLog(@"Errore nell'url"); exit(0);}
    
    AutoDownloadImageView *img = [[AutoDownloadImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 160)URL:url persistency:YES forceDownload:NO];

    [img setDelegate:self];
    [cell.contentView addSubview:img];

    //setta lo stile con cui vengono selezionate le righe
    //[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //cell.selectionStyle = UITableViewCellSelectionStyleGray;
    //setta il stile con cui vengono selezionate le righe
    //UIImageView *selBgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cella_bg.png"]];
    //cell.selectedBackgroundView = selBgView;
    
    cell.titolo.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"title"];
	cell.link.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"link"];
    cell.descrizione.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"description"];
    [cell retain];
    return cell;
    
}

-(void)autoDownloadImageViewFinishDownloading:(AutoDownloadImageView *)autoDowload {
}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// ricaviamo il link dell'elemento selezionato
	NSString *paths = [[elencoFeed objectAtIndex:indexPath.row] objectForKey: @"link"];
    //NSString *titolo = [[elencoFeed objectAtIndex:indexPath.row] objectForKey: @"title"];
    //NSString *path = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"imageURL"];
    //NSString *descrizione = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"description"];
    
    // ripuliamo il link da spazi, return e tabs
	paths = [paths stringByReplacingOccurrencesOfString:@" " withString:@""];
	paths = [paths stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	paths = [paths stringByReplacingOccurrencesOfString:@"	" withString:@""];
    /*
    // ripuliamo il link da spazi, return e tabs
    path = [path stringByReplacingOccurrencesOfString:@" " withString:@""];
    path = [path stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    path = [path stringByReplacingOccurrencesOfString:@"	" withString:@""];
    NSURL *imageUrl = [NSURL URLWithString:path];
     */
    
    /*
    controller.titoloArticolo = titolo;
    controller.descrizioneArticolo = descrizione;
    controller.imageArticoloView = imageUrl;
    */
    
    // apriamo la nuova vista
    ArticoloCommentiViewController *controller =[[ArticoloCommentiViewController alloc] initWithNibName:@"ArticoloCommentiViewController" bundle:nil];
    controller.urlParserView = paths;
    [self.navigationController pushViewController:controller animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}

- (void)dealloc {
    [AutoDownloadImageView release];
	[elencoFeed release];
	[item release];
    [AutoDownloadImageView release];
    [imageURL release];
    [description release];
    [link release];
    [path release];
    [listaTabella release];
    [URLparser release];
    [spinner release];
    [spinnerView release];
    [super dealloc];
}


@end
